//
//  ScoreTeacherSelectViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-7-15.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "ScoreTeacherSelectViewController.h"
#import "NetworkAccessManager.h"
#import "AppDelegate.h"
#import "ScoreCollectionViewCell.h"
#import "ChildInfo.h"
#import "UIImageView+AFNetworking.h"
#import "UIAlertView+Kirinrin.h"

@interface ScoreTeacherSelectViewController ()
@property (strong, nonatomic)AppDelegate *appDelegate;


@end

@implementation ScoreTeacherSelectViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [self.collectionView setAllowsMultipleSelection:YES];
    
    if (self.selectedIndexPathArray) {
        for (NSIndexPath *indexPath in self.selectedIndexPathArray) {
            [self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition: UICollectionViewScrollPositionTop];
        }
    }
//    [self loadRemoteData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadRemoteData{
    NSString *uriString = [NSString stringWithFormat:@"Child/%@/queryClassChild.json", self.appDelegate.user[@"kClassId"]];
    NSDictionary *parameters = @{@"key": self.appDelegate.accessKey};
    
    [[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            
            self.collectionData = [ChildInfo sortByGenderAndNameFromChildListFromeRemoteData:responseObject[@"data"]];
            [self.collectionView reloadData];
            if (self.selectedIndexPathArray) {
                for (NSIndexPath *indexPath in self.selectedIndexPathArray) {
                    [self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition: UICollectionViewScrollPositionTop];
                }
            }
        }else{
            [UIAlertView alertWithRemoteError:resultCode];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        [UIAlertView alertWithNetworkError];
    }];
}

#pragma mark - actions
- (IBAction)doneAction:(id)sender {

    [self.delegate scoreTeacherSelectViewControlleWasDone:self.selectedIndexPathArray childArray:self.selectedChildArray unSelectedChildArray: self.unSelectedChildArray];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)cancelAction:(id)sender {
    [self.selectedChildArray removeAllObjects];
    self.unSelectedChildArray = [NSMutableArray arrayWithArray:self.collectionData];
    [self.delegate scoreTeacherSelectViewControlleWasDone:nil childArray:nil unSelectedChildArray:nil];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.collectionData[section] count];
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"Cell";
    ScoreCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
//    [cell.photo setImage:[UIImage imageNamed:@"imageUserPhotoDefault"]];
    ChildInfo *child = self.collectionData[indexPath.section][indexPath.item];
    [cell.name setText:child.name];
    [cell.photo setImageWithURL:child.photoUrl placeholderImage:[UIImage imageNamed:@"imageUserPhotoDefault"]];
    return cell;
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return [self.collectionData count];
}
/*
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
*/
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"selected item at %@", indexPath);
    [self.selectedIndexPathArray addObject:indexPath];
    
    [self.selectedChildArray addObject:self.collectionData[indexPath.section][indexPath.item]];
    [self.unSelectedChildArray removeObject:self.collectionData[indexPath.section][indexPath.item]];
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"dselected item at %@", indexPath);
    [self.selectedIndexPathArray removeObject:indexPath];
    [self.selectedChildArray removeObject:self.collectionData[indexPath.section][indexPath.item]];
    [self.unSelectedChildArray addObject:self.collectionData[indexPath.section][indexPath.item]];
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    static NSString * cellId = @"Header";
    UICollectionReusableView* cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind                   withReuseIdentifier:cellId                             forIndexPath:indexPath];
    UILabel *headerLabel = (UILabel *)[cell viewWithTag:100];
    if (indexPath.section == 0) {
        [headerLabel setText:@"女生"];
    }else {
        [headerLabel setText:@"男生"];
    }
    
    return cell;
}

@end
